// pages/order/order-list/index.js
const app = getApp();
const db = wx.cloud.database()
const product = db.collection('order_info')
const _ = db.command
const dataPageNum = 10
Page({
  data: {
    color: app.ext.color,
    orderOperate: ["全部", "待付款", "待发货", "待收货", "已完成"],
    orderOperateIndex: 0,
    page: 1,
    orderlist: [],
    is_all: 0,
    dataNum : 0,
    state : 0,
    loadCount: 0,
    showCount: 0,
    back:0
  },
  onLoad: function (options) {
    wx.removeStorageSync('order-type');
    // 0：代付款 1：代发货 2：待收货 3：退换货(从个人中心四个订单按钮跳转过来)
    if (options.type) {
      this.setData({
        type: Number(options.type)
      })
    }
    this.setData({
      loadCount: this.data.loadCount + 1
    })

  },
  onShow: function () {
    if(this.data.back==0){
      this.setData({
        showCount: this.data.showCount + 1
      })
      if (this.data.showCount == this.data.loadCount) {
        this.setData({
          dataNum: 0
        })
      }
      this.changeTab();
      this.setData({
        back:1
      })
    }else{
      this.changeTab();
      // this.getOrderList();
    }
    
  },
  changeTab(e) {
    console.log("test1")
    console.log(this.data.type)
    let index = e ? Number(e.currentTarget.dataset.index) : 0;
    if (e) {
      console.log("test2")
      this.setData({
        type: 'undefined'
      })
    }

    // this.data.state = e
    if (index == 0) {
      index = 0
    }
    if (index == 1 || this.data.type == 0) {
      this.setData({
        state : 0
      })
      index = 1;
    }
    if (index == 2 || this.data.type == 1) {
      this.setData({
        state: 1
      })
      index = 2;
    }
    if (index == 3 || this.data.type == 2) {
      this.setData({
        state: 2
      })
      index = 3;
    }
   
    if (index == 4 ||this.data.type == 3) {
      this.setData({
        state: 3
      })
      index = 4;     }
    if (wx.getStorageSync('order-type')) {
      console.log(wx.getStorageSync('order-type'))
 
      const obj = wx.getStorageSync('order-type');
      console.log(obj.state)
      this.data.state = obj.state;
      index = obj.index;
      wx.removeStorageSync('order-type');
    }
    this.setData({
      page: 1,
      orderlist: [],
      orderOperateIndex: index,
      dataNum:0
    })
    console.log(this.data.type)
    console.log("index"+index)
    if(index==0){
      this.getAllOrderList();
    }else{
      this.getOrderList();
    }  
  },
  getAllOrderList() {
    let orderlist = this.data.orderlist;
    //TODO 获取订单数据
    db.collection('order_info').orderBy('createtime', 'desc').where({
      openid: wx.getStorageSync("openid"), diyId: wx.getStorageSync('diyId')
    }).skip(this.data.dataNum).limit(dataPageNum).get().then(res => {
      console.log(res.data);
      this.data.page++;
      const DATA = res.data;
      orderlist = orderlist.concat(DATA);
      this.setData({
        dataNum: this.data.dataNum + dataPageNum
      })
      if (orderlist.length != this.data.dataNum) this.data.is_all = 1;
      this.setData({
        page: this.data.page,
        is_all: this.data.is_all,
        orderlist: orderlist
      });
    })


  },
  getOrderList() {
    let orderlist = this.data.orderlist;
    console.log("1111111111111")
    console.log(wx.getStorageSync("openid"))
    console.log(this.data.state)
    //TODO 获取订单数据
    db.collection('order_info').orderBy('createtime', 'desc').where({
      openid : wx.getStorageSync("openid"),
      state : this.data.state,
      diyId: wx.getStorageSync('diyId')
    }).skip(this.data.dataNum).limit(dataPageNum).get().then(res => {
      console.log(res.data);
      this.data.page++;
      const DATA = res.data;
      orderlist = orderlist.concat(DATA);
      this.setData({
        dataNum: this.data.dataNum + dataPageNum
      })
      if (orderlist.length != this.data.dataNum) this.data.is_all = 1;
      this.setData({
        page: this.data.page,
        is_all: this.data.is_all,
        orderlist: orderlist
      });
    })


  },
  goDetail(e) {
    console.log(this.data.state)
    wx.setStorageSync('order-type', {
      state: this.data.state,
      index: this.data.orderOperateIndex
    });
    wx.navigateTo({
      url: `../order-detail/index?order_id=${e.currentTarget.dataset.id}`
    })
  },
  operate(e) {
    const type = Number(e.currentTarget.id);
    switch (type) {
      case 0: // 确认收货
        {
          const order_id = e.detail.value.order_id;
          // wx.doodoo.fetch(`/shop/api/shop/order/order/update`, {
          //   method: 'GET',
          //   data: {
          //     id: order_id,
          //     status: 2
          //   }
          // }).then(res => {
          //   if (res && res.data.errmsg == 'ok') {
          //     this.setData({
          //       page: 1,
          //       orderlist: []
          //     })
          //     this.getOrderList();
          //   }
          // })
          break;
        };
      case 1: // 付款
        {
          const order_id = e.currentTarget.dataset.order_id;
          const trade_id = e.detail.value.trade_id;
          // wx.doodoo.fetch(`/app/pay/wxpay/index?id=${trade_id}`).then(res => {
          //   if (res && res.data.errmsg == 'ok') {
          //     let response = res.data.data;
          //     let timeStamp = response.timeStamp;
          //     //可以支付
          //     wx.requestPayment({
          //       timeStamp: timeStamp.toString(),
          //       nonceStr: response.nonceStr,
          //       package: response.package,
          //       signType: response.signType,
          //       paySign: response.paySign,
          //       success: () => {
          //         this.send_tplmsg(response.package, order_id); // 支付成功，发送支付成功模板
          //         this.setData({
          //           page: 1,
          //           orderlist: []
          //         })
          //         this.getOrderList();
          //       }
          //     });
          //   } else {
          //     wx.showModal({
          //       title: "提示",
          //       content: res.data.data,
          //       showCancel: false
          //     });
          //   }
          // });
          break;
        };
      case 2: // 取消订单
        {
          const order_id = e.detail.value.order_id;
          const that = this;
          wx.showModal({
            title: "提示",
            content: "确定取消订单吗？",
            success: function (res) {
              if (res.confirm) {
                // wx.doodoo.fetch(`/shop/api/shop/order/order/update`, {
                //   method: 'GET',
                //   data: {
                //     id: order_id,
                //     status: -1
                //   }
                // }).then(res => {
                //   if (res && res.data.errmsg == 'ok') {
                //     that.setData({
                //       page: 1,
                //       orderlist: []
                //     })
                //     that.getOrderList();
                //   }
                // })
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            }
          })
          break;
        };
      case 3: // 查看物流
        {
          wx.setStorageSync('order-type', {
            state: this.data.state,
            index: this.data.orderOperateIndex
          });
          const order = e.currentTarget.dataset.data;
          wx.navigateTo({
            url: `../logistics/index?order=${JSON.stringify(order)}`
          })
          break;
        };
    }
  },
  // 发送模板消息
  send_tplmsg: function (formId, order_id) {
    formId = formId.substring(10);
    // wx.doodoo.fetch("/api/order/sendPayTpl", {
    //   method: "GET",
    //   data: {
    //     formId: formId,
    //     orderId: order_id
    //   }
    // }, res => {
    //   console.log("发送模板消息", res);
    // });
  },
  onReachBottom: function () {
    if (!this.data.is_all) {
      this.getOrderList();
    }
  },
  onPullDownRefresh: function () {
    setTimeout(() => {
      this.setData({
        page: 1,
        orderlist: [],
        is_all: 0,
        dataNum : 0
      })
      this.getOrderList();
      wx.stopPullDownRefresh();
    }, 500)
  }
})